<?php

class Silk_Zgb_Model_Dealer extends Mage_Core_Model_Abstract
{
    const ATTRIBUTE_ID = 191;

    protected function _construct(){

       $this->_init("zgb/dealer");

    }

    public function toOptionArray()
    {
        //$_collection = $this->getCollection();
        $resource = Mage::getSingleton('core/resource');
        $db = $resource->getConnection('core_read');
        $sql = "SELECT id,`name` FROM zgb_dealer WHERE 1 ORDER BY CONVERT( `name` USING gbk ) COLLATE gbk_chinese_ci ASC";
        $query = $db->query($sql);
        $_items = $query->fetchAll();

    	$_options = array();
    	foreach($_items as $_item)
    	{
    		$_options[] = array('value'=>$_item['id'],'label'=>$_item['name']);
    	}
    	return $_options;
    }

    public function loadByAdminId($id)
    {
        $collection = $this->getCollection();
        $collection->addFieldToFilter('admin_id', array('eq'=>$id));
        return $collection->getFirstItem();
    }

    public function getWebsiteBySku($id)
    {
        $attribute_id = Silk_Zgb_Helper_Data::DEALER_ID;
        if($id)
        {
            $sql = "SELECT DISTINCT(store_id) FROM `catalog_product_entity_int` WHERE store_id!=0 AND entity_id='{$id}' AND attribute_id='{$attribute_id}' AND `value`='{$this->getId()}'";
        }
        else
        {
            $sql = "SELECT DISTINCT(store_id) FROM `catalog_product_entity_int` WHERE store_id!=0 AND attribute_id='{$attribute_id}' AND `value`='{$this->getId()}'";
        }

        $resource = Mage::getSingleton('core/resource');
        $db = $resource->getConnection('core_read');

        $query = $db->query($sql);
        $items = $query->fetchAll();
        $websites = array();

        foreach($items as $item)
        {
            $store = Mage::getModel('core/store')->load($item['store_id']);
            if($store && $store->getId())
            {
                $websites[] = $store->getId();
            }
        }
        return $websites;
    }

    public function getWarehouseCollection()
    {
        return Mage::getModel('zgb/warehouse')->getCollection()->addFieldToFilter('dealer_id', array('eq'=>$this->getId()));
    }

    public function getWarehouseIds()
    {
        $collection = $this->getWarehouseCollection();
        $ids = array();
        foreach($collection as $item)
        {
            $ids[] = $item->getId();
        }
        return $ids;
    }
}
	 